<template>
  <a-upload
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="actionUrl"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="avatarImg" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>
<script>
export default {
  data() {
    return {
      actionUrl: this.$host + '/api/UploadFile',
      loading: false,
      imageUrl: ''
    }
  },
  props: {
    imageArr: {
      type: Array,
      default: () => []
    },
    propImageUrl: {
      type: String,
      default: ''
    }
  },
  watch: {
    propImageUrl(val) {
      this.imageUrl = this.propImageUrl
    }
  },
  methods: {
    getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        this.$emit('getAvatar', info.file.response.data.fileName)
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>
<style lang="less" scoped>
.avatarImg {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
.ant-upload-picture-card-wrapper {
  width: auto !important;
}
</style>
